<template>
  <div class="interview-container">
    <div class="interview-main">
      <!-- 左侧 - 情绪与行为分析面板 -->
      <div class="analysis-panel">
        <div class="panel-section">
          <div class="panel-header">
            <robot-outlined />
            <span>{{
              language === 'chinese' ? '微表情情感分析' : 'Micro-Expression Analysis'
            }}</span>
          </div>
          <div
            class="emotion-chart"
            style="
              height: 260px;
              display: flex;
              flex-direction: column;
              justify-content: flex-start;
            "
          >
            <v-chart class="chart" :option="radarOption" autoresize style="height: 160px" />
            <div class="emotion-percentages" style="margin-top: 16px">
              <div class="emotion-percentage-item">
                <span class="emotion-label">{{
                  language === 'chinese' ? '自信' : 'Confident'
                }}</span>
                <div class="emotion-bar">
                  <div
                    class="emotion-bar-fill confident"
                    :style="{ width: emotionPercentages.confident + '%' }"
                  ></div>
                </div>
                <span class="emotion-value">{{ emotionPercentages.confident }}%</span>
              </div>
              <div class="emotion-percentage-item">
                <span class="emotion-label">{{ language === 'chinese' ? '冷静' : 'Calm' }}</span>
                <div class="emotion-bar">
                  <div
                    class="emotion-bar-fill calm"
                    :style="{ width: emotionPercentages.calm + '%' }"
                  ></div>
                </div>
                <span class="emotion-value">{{ emotionPercentages.calm }}%</span>
              </div>
              <div class="emotion-percentage-item">
                <span class="emotion-label">{{ language === 'chinese' ? '紧张' : 'Nervous' }}</span>
                <div class="emotion-bar">
                  <div
                    class="emotion-bar-fill nervous"
                    :style="{ width: emotionPercentages.nervous + '%' }"
                  ></div>
                </div>
                <span class="emotion-value">{{ emotionPercentages.nervous }}%</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 面部行为分析 -->
        <div class="panel-section">
          <div class="panel-header">
            <aim-outlined />
            <span>{{
              language === 'chinese'
                ? '面部行为检测（当前回答）'
                : 'Facial Behavior Detection（current answer）'
            }}</span>
          </div>
          <div class="face-actions-grid">
            <div
              v-for="(action, index) in faceActions"
              :key="index"
              class="action-grid-item"
              :class="{
                'action-active':
                  action.count > 0 || currentSpeakingActionCounts.faceActions[index] > 0,
                'current-speaking-active': currentSpeakingActionCounts.faceActions[index] > 0,
              }"
            >
              <div class="action-icon" :style="{ backgroundColor: action.color }">
                <component :is="action.icon" />
              </div>
              <div class="action-info">
                <div class="action-name">{{ action.name }}</div>
                <div class="action-count">
                  {{ action.count }} {{ language === 'chinese' ? '次' : 'times' }}
                  <span
                    class="current-speaking-count"
                    v-if="currentSpeakingActionCounts.faceActions[index] > 0"
                  >
                    +{{ currentSpeakingActionCounts.faceActions[index] }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 语音分析 -->
        <div class="panel-section">
          <div class="panel-header">
            <sound-outlined />
            <span>{{
              language === 'chinese' ? '语音分析（当前回答）' : 'Voice Analysis（current answer）'
            }}</span>
          </div>

          <div class="voice-analysis">
            <div class="voice-metric">
              <div style="display: flex">
                <div class="metric-label">
                  {{ language === 'chinese' ? '语速：' : 'Speech Rate：' }}
                </div>
                <div class="meter-label" style="">
                  {{ commonStore.audioSpeed }}
                </div>
              </div>
            </div>
            <div class="voice-metric">
              <div style="display: flex; align-items: center">
                <div class="metric-label">
                  {{ language === 'chinese' ? '情感：' : 'Emotion：' }}
                </div>
                <div class="meter-label">
                  {{ commonStore.audioEmotion }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 躯体检测 -->
        <div class="panel-section">
          <div class="panel-header">
            <experiment-outlined />
            <span>{{
              language === 'chinese'
                ? '躯体动作检测（当前回答）'
                : 'Body Movement Detection（current answer）'
            }}</span>
          </div>
          <div class="body-actions-grid">
            <div
              v-for="(action, index) in bodyActions"
              :key="index"
              class="action-grid-item"
              :class="{
                'action-active':
                  action.count > 0 || currentSpeakingActionCounts.bodyActions[index] > 0,
                'current-speaking-active': currentSpeakingActionCounts.bodyActions[index] > 0,
              }"
            >
              <div class="action-icon" :style="{ backgroundColor: action.color }">
                <component :is="action.icon" />
              </div>
              <div class="action-info">
                <div class="action-name">{{ action.name }}</div>
                <div class="action-count">
                  {{ action.count }} {{ language === 'chinese' ? '次' : 'times' }}
                  <span
                    class="current-speaking-count"
                    v-if="currentSpeakingActionCounts.bodyActions[index] > 0"
                  >
                    +{{ currentSpeakingActionCounts.bodyActions[index] }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="interview-controls-container" v-if="!isStartInterview">
          <a-button
            v-if="language === 'chinese'"
            type="primary"
            @click="startInterview"
            class="start-btn"
            >开始面试
            <template #icon>
              <play-circle-outlined />
            </template>
          </a-button>
          <a-button v-else type="primary" @click="startInterview" class="start-btn">
            Start Interview
            <template #icon>
              <play-circle-outlined />
            </template>
          </a-button>
        </div>
        <div class="interview-timer" v-else>
          <div class="interview-duration">
            <clock-circle-outlined />
            <span>{{ formatDuration(currentDuration) }}</span>
          </div>
        </div>
      </div>

      <!-- 中间 - 虚拟数字人和用户摄像头区域 -->
      <div class="center-panel">
        <div
          class="digital-human-container"
          :style="{ backgroundImage: `url(${modernOfficeBackground})` }"
        >
          <div class="interviewer-status">
            <span class="status-indicator"></span>
            <span>{{ getInterviewerStatusText() }}</span>
          </div>

          <video :src="interviewerMp4" autoplay loop muted class="digital-human" />

          <!-- 添加面试官生成问题的加载动画 -->
          <div class="generating-question-overlay" v-if="isGeneratingQuestion">
            <div class="generating-question-content">
              <loading-outlined style="font-size: 32px; color: #fff" spin />
              <p>{{ language === 'chinese' ? '正在生成问题...' : 'Generating question...' }}</p>
            </div>
          </div>

          <div class="interviewer-info">
            <div class="interviewer-avatar">
              <img :src="interviewerAvatar" alt="面试官" />
            </div>
            <div class="interviewer-details">
              <h3>{{ language === 'chinese' ? 'Lisa Chen' : 'John Smith' }}</h3>
              <p>
                {{
                  language === 'chinese'
                    ? '高级人力资源面试官'
                    : 'Senior Human Resources Interviewer'
                }}
              </p>
            </div>
          </div>
        </div>

        <div class="user-camera-container">
          <div class="camera-header">
            <video-camera-outlined />
            <span>{{ language === 'chinese' ? '面部动作检测' : 'Facial Action Detection' }}</span>
            <div class="recording-indicator" :class="{ 'video-recording': isMonitoringPageLeave }">
              {{
                isMonitoringPageLeave
                  ? language === 'chinese'
                    ? '● 监控中'
                    : '● Monitoring'
                  : '● MON'
              }}
            </div>
          </div>
          <div class="camera-content">
            <FaceDetection
              ref="faceRef"
              interview-type="=1"
              @emotion-detected="handleEmotionDetected"
              @face-action-detected="handleFaceActionDetected"
            />
          </div>
          <div class="camera-tips">
            <info-circle-outlined />
            <span>{{
              language === 'chinese'
                ? '提示：保持面部在画面中，系统正在分析您的面部表情和肢体动作'
                : 'Tip: Keep your face in frame, the system is analyzing your facial expressions and body language'
            }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧 - 对话区 -->
      <div class="chat-panel">
        <AudioChat
          ref="audioChatRef"
          :is-start-interview="isStartInterview"
          :language="language"
          :messages="messages"
          interview-type="1"
          :interviewer-avatar="interviewerAvatar"
          :interview-end="interviewEnd"
          :on-interviewer-status="onInterviewerStatus"
          :add-message="addMessage"
          :start-speaking="startSpeaking"
          :stop-speaking="stopSpeaking"
          :show-generating-question="showGeneratingQuestion"
          :hide-generating-question="hideGeneratingQuestion"
        />
      </div>
    </div>

    <!-- 面试结束确认弹窗 -->
    <a-modal
      v-model:visible="exitConfirmVisible"
      :title="language === 'chinese' ? '确认结束面试' : 'Confirm End Interview'"
      :footer="null"
      :maskClosable="false"
      class="custom-modal exit-modal"
    >
      <div class="modal-content">
        <div class="modal-icon warning">
          <exclamation-circle-outlined />
        </div>
        <div class="modal-message">
          <p v-if="language === 'chinese'">退出当前面试后，无法获取本次面试的结果分析哦！</p>
          <p v-else>
            After exiting this interview, you will not be able to get the analysis of this
            interview!
          </p>
        </div>
        <div class="modal-footer">
          <a-button @click="exitConfirmVisible = false">
            {{ language === 'chinese' ? '取消' : 'Cancel' }}
          </a-button>
          <a-button type="primary" danger @click="cancelInterview">
            {{ language === 'chinese' ? '确认退出' : 'Confirm Exit' }}
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 面试完成结果弹窗 -->
    <a-modal
      v-model:visible="resultModalVisible"
      :title="language === 'chinese' ? '面试已完成' : 'Interview Completed'"
      :footer="null"
      :maskClosable="false"
      class="custom-modal result-modal"
    >
      <div class="modal-content">
        <div class="modal-icon success">
          <check-circle-outlined />
        </div>
        <div class="modal-message">
          <p v-if="language === 'chinese'">
            当前面试已结束，请稍后到技术面试记录页面查看当前模拟面试的分析报告。
          </p>
          <p v-else>
            The interview has ended. Please check the Tec Interview Records page later to view the
            analysis report.
          </p>
        </div>
        <div class="modal-footer">
          <a-button type="primary" @click="goToHomePageOrFullScreen">
            {{ language === 'chinese' ? '确定' : 'Confirm' }}
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 退出面试按钮 (固定在右上角) -->
    <div class="exit-button">
      <a-button danger class="control-btn" @click="showExitConfirmModal">
        <template #icon>
          <close-circle-outlined />
        </template>
        {{ language === 'chinese' ? '结束面试' : 'End Interview' }}
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, watchEffect, reactive, computed, onMounted } from 'vue'
import AudioChat from '@/components/AudioChat.vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  SoundOutlined,
  CloseCircleOutlined,
  RobotOutlined,
  VideoCameraOutlined,
  InfoCircleOutlined,
  AimOutlined,
  ExperimentOutlined,
  PlayCircleOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  SkinOutlined,
  LoadingOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import modernOfficeBackground from '@/assets/modern-office-background.webp'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { RadarChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import FaceDetection from '@/components/FaceDetection.vue'
import { analyzeHrInterviewUsingPost, cancelHrInterviewUsingGet } from '@/api/hrInterviewController'
import { useCommonStore } from '@/stores/useCommonStore'
import { getLocalCache } from '@/utils/LocalStorageUtils.js'

const commonStore = useCommonStore()
// 注册 ECharts 组件
use([CanvasRenderer, RadarChart, TitleComponent, TooltipComponent, LegendComponent])

//重定向路由
let redirect = null

// 使用 defineProps 接收路由参数
const props = defineProps({
  language: {
    type: String,
    required: true, // 如果 language 是必传的
  },
})

// 页面监控相关变量
const pageLeaveCount = ref(0)
const MAX_PAGE_LEAVE_COUNT = 5
const isMonitoringPageLeave = ref(false)
const isCurrentlyAway = ref(false) // 跟踪用户是否当前离开了页面

// 控制问题生成加载动画的显示
const isGeneratingQuestion = ref(false)

// 显示问题生成加载动画
const showGeneratingQuestion = () => {
  isGeneratingQuestion.value = true
}

// 隐藏问题生成加载动画
const hideGeneratingQuestion = () => {
  isGeneratingQuestion.value = false
}

//hr面试id
const hrInterviewId = ref('')
const route = useRoute()
const router = useRouter()

// 使用 watchEffect 监听 route.query 的变化
watchEffect(() => {
  hrInterviewId.value = route.query.hrInterviewId as any
})

//面试官视频
const videoMap = {
  1: {
    // interviewerId = 1
    1: () => import('../../../../public/mp4/interviewer1_01.mp4'), //准备
    2: () => import('../../../../public/mp4/interviewer1_02.mp4'), //说话
    3: () => import('../../../../public/mp4/interviewer1_03.mp4'), //倾听
  },
  2: {
    // interviewerId = 2
    1: () => import('../../../../public/mp4/interviewer2_01.mp4'), //准备
    2: () => import('../../../../public/mp4/interviewer2_02.mp4'), //说话
    3: () => import('../../../../public/mp4/interviewer2_03.mp4'), //倾听
  },
  3: {  // interviewerId = 3
    1: () => import('../../../../public/mp4/interviewer3_01.mp4'), //准备
    2: () => import('../../../../public/mp4/interviewer3_02.mp4'), //说话
    3: () => import('../../../../public/mp4/interviewer3_03.mp4'), //倾听
  },
  4: {  // interviewerId = 4
    1: () => import('../../../../public/mp4/interviewer4_01.mp4'), //准备
    2: () => import('../../../../public/mp4/interviewer4_02.mp4'), //说话
    3: () => import('../../../../public/mp4/interviewer4_03.mp4'), //倾听
  },
  5: {
    // interviewerId = 5
    1: () => import('../../../../public/mp4/interviewer5_01.mp4'), //准备
    2: () => import('../../../../public/mp4/interviewer5_02.mp4'), //说话
    3: () => import('../../../../public/mp4/interviewer5_03.mp4'), //倾听
  },
  6: {
    // interviewerId = 6
    1: () => import('../../../../public/mp4/interviewer6_01.mp4'), //准备
    2: () => import('../../../../public/mp4/interviewer6_02.mp4'), //说话
    3: () => import('../../../../public/mp4/interviewer6_03.mp4'), //倾听
  }
}

// 面试官头像
const interviewerAvatar = ref('')
// 面试官序号
const interviewerId = ref('')

//面试官虚拟数字人
const interviewerMp4 = ref('')

// 控制弹窗显示状态
const exitConfirmVisible = ref(false)
const resultModalVisible = ref(false)

//开启ai语音说话状态
//0: 没有开始面试，1：生成问题 2：提问 3:倾听用户回答 4:面试结束
const interviewerStatus = ref(0)
//当前面试时长
const currentDuration = ref(1) // 秒
//是否开启面试
const isStartInterview = ref(false)
//记录定时器id
let timer = null
//获取语音面试组件中的建立连接
const audioChatRef = ref(null)
//ws连接
let websocket = null

//表情检测标签
const faceRef = ref(null)

// 情感数据初始化
const emotionData = reactive({
  confident: 0,
  calm: 0,
  nervous: 0,
})

// 雷达图 数据
const emotionPercentages = computed(() => {
  const total = emotionData.confident + emotionData.calm + emotionData.nervous
  if (total === 0) {
    return { confident: 0, calm: 0, nervous: 0 }
  }
  return {
    confident: Math.round((emotionData.confident / total) * 100),
    calm: Math.round((emotionData.calm / total) * 100),
    nervous: Math.round((emotionData.nervous / total) * 100),
  }
})

// 雷达图配置（动态）
const radarOption = computed(() => {
  return {
    tooltip: {
      show: true,
      trigger: 'item',
      backgroundColor: '#fff',
      borderColor: '#4795ea',
      borderWidth: 1,
      textStyle: {
        color: '#333',
        fontSize: 13,
      },
      position: function (point, params, dom, rect, size) {
        // 居中显示tooltip
        var viewWidth = size.viewSize[0]
        var boxWidth = size.contentSize[0]
        var viewHeight = size.viewSize[1]
        var boxHeight = size.contentSize[1]
        return [
          Math.max((viewWidth - boxWidth) / 2, 10),
          Math.max((viewHeight - boxHeight) / 2, 10),
        ]
      },
      formatter: function (params) {
        if (params.value) {
          const total = params.value.reduce((a, b) => a + b, 0)
          const percent =
            total === 0 ? [0, 0, 0] : params.value.map((v) => Math.round((v / total) * 100))
          return (
            `<div style='padding:4px 8px;'>` +
            `<b>${params.name}</b><br/>` +
            `${props.language === 'chinese' ? '自信' : 'Confident'}: ${params.value[0]} (${
              percent[0]
            }%)<br/>` +
            `${props.language === 'chinese' ? '冷静' : 'Calm'}: ${params.value[1]} (${
              percent[1]
            }%)<br/>` +
            `${props.language === 'chinese' ? '紧张' : 'Nervous'}: ${params.value[2]} (${
              percent[2]
            }%)</div>`
          )
        }
        return ''
      },
      extraCssText: 'box-shadow:0 2px 8px rgba(71,149,234,0.15);border-radius:8px;',
    },
    radar: {
      indicator: [
        { name: props.language === 'chinese' ? '自信' : 'Confident', min: 0, max: 100 },
        { name: props.language === 'chinese' ? '冷静' : 'Calm', min: 0, max: 100 },
        { name: props.language === 'chinese' ? '紧张' : 'Nervous', min: 0, max: 100 },
      ],
      radius: 70, // 调小半径，避免遮挡
      center: ['50%', '66%'], // 向上偏移，给下方留空间
      splitNumber: 4,
      axisName: {
        color: '#333',
        fontSize: 12,
      },
      splitArea: {
        areaStyle: {
          color: ['#f7f8fc', '#eef1f8', '#e5e9f4', '#dce3f0'],
          shadowColor: 'rgba(0, 0, 0, 0.05)',
          shadowBlur: 10,
        },
      },
      axisLine: {
        lineStyle: {
          color: '#cccccc',
        },
      },
      alignTicks: false,
    },
    series: [
      {
        name: props.language === 'chinese' ? '情感分析' : 'Emotion Analysis',
        type: 'radar',
        data: [
          {
            value: [emotionData.confident, emotionData.calm, emotionData.nervous],
            name: props.language === 'chinese' ? '面试表现' : 'Interview Performance',
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#4795ea',
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(71, 149, 234, 0.5)',
                  },
                  {
                    offset: 1,
                    color: 'rgba(71, 149, 234, 0.1)',
                  },
                ],
              },
            },
            lineStyle: {
              width: 2,
            },
          },
        ],
      },
    ],
    animation: true,
  }
})

// 面部行为数据
const faceActions = reactive([
  {
    name: props.language === 'chinese' ? '眨眼' : 'Eye Blink',
    count: 0,
    icon: EyeOutlined,
    color: '#36cfc9',
  },
  {
    name: props.language === 'chinese' ? '抿嘴' : 'Mouth Pucker',
    count: 0,
    icon: SkinOutlined,
    color: '#ff7a45',
  },
  {
    name: props.language === 'chinese' ? '左斜视' : 'Look Left',
    count: 0,
    icon: AimOutlined,
    color: '#9254de',
  },
  {
    name: props.language === 'chinese' ? '右斜视' : 'Look Right',
    count: 0,
    icon: AimOutlined,
    color: '#597ef7',
  },
])

// 躯体动作数据
const bodyActions = reactive([
  {
    name: props.language === 'chinese' ? '摸耳朵' : 'Touch Ear',
    count: 0,
    icon: SkinOutlined,
    color: '#ffa940',
  },
  {
    name: props.language === 'chinese' ? '摸鼻子' : 'Touch Nose',
    count: 0,
    icon: SkinOutlined,
    color: '#73d13d',
  },
])

// 当前语音过程中的动作计数
const currentSpeakingActionCounts = reactive({
  faceActions: [0, 0, 0, 0], // 对应四种面部动作的临时计数
  bodyActions: [0, 0], // 对应两种躯体动作的临时计数
})

/**
 * 面试所有对话内容数组
 */
const messages = ref([
  {
    sender: 'ai',
    text:
      props.language === 'chinese'
        ? '你好，准备完成后点击左下角按钮开始面试。'
        : 'Hi, click the button in the lower left corner to start the tec.',
  },
])

/**
 * 记录面试消息
 * @param message
 */
const addMessage = (message) => {
  messages.value.push(message)
}

/**
 * 面试官状态 回调函数
 */
const onInterviewerStatus = async (status) => {
  interviewerStatus.value = status
  //切换虚拟数字人
  const module = await videoMap[interviewerId.value][status]()
  interviewerMp4.value = module.default
}

/**
 * 获取面试官状态文本
 */
function getInterviewerStatusText() {
  switch (interviewerStatus.value) {
    case 0:
      return props.language === 'chinese'
        ? '点击下方按钮开始面试'
        : 'Click the button below to start interview'
    case 1:
      return props.language === 'chinese'
        ? '面试官正在生成问题'
        : 'Interviewer is generating questions'
    case 2:
      return props.language === 'chinese' ? '面试官正在提问' : 'Interviewer is asking a question'
    case 3:
      return props.language === 'chinese'
        ? '面试官正在倾听您的回答'
        : 'Interviewer is listening to your answer'
    case 4:
      return props.language === 'chinese' ? '本次面试已结束' : 'This interview has ended'
    default:
      return props.language === 'chinese' ? '面试官已连接' : 'Interviewer connected'
  }
}

/**
 * 显示退出确认弹窗
 */
const showExitConfirmModal = () => {
  exitConfirmVisible.value = true
}

/**
 * 跳转到首页或全流程面试页面
 */
const goToHomePageOrFullScreen = () => {
  if (redirect) {
    router.replace(redirect)
  } else {
    router.replace('/')
  }
}

/**
 * 开始面试
 */
const startInterview = async () => {
  //调用AudioChat子组件中的方法
  audioChatRef.value.startAiInterview()
  //改变面试官状态
  interviewerStatus.value = 1

  //切换虚拟数字人
  const module = await videoMap[interviewerId.value][1]()
  interviewerMp4.value = module.default

  //开启面试官加载动画
  showGeneratingQuestion()

  //开始微表情情感检测
  faceRef.value.runDetection()
  isStartInterview.value = true
  //开启定时器，记录面试时间
  timer = setInterval(() => {
    currentDuration.value += 1
  }, 1000)
  //获取AudioChat子组件中的ws连接
  websocket = audioChatRef.value.createWsConnection()

  // 如果是全流程面试，开始页面监控
  if (redirect) {
    startPageLeaveMonitoring()
  }
}

/**
 * 结束面试
 */
const interviewEnd = async () => {
  //停止微表情表情检测
  faceRef.value.stopDetection()

  // 结束面试逻辑
  isStartInterview.value = false
  //关闭退出确认弹窗
  exitConfirmVisible.value = false
  // 显示结果弹窗
  resultModalVisible.value = true
  //将面试官状态改为结束
  interviewerStatus.value = 4

  //切换虚拟数字人
  const module = await videoMap[interviewerId.value][1]()
  interviewerMp4.value = module.default

  // 如果正在监控页面离开，停止监控
  if (isMonitoringPageLeave.value) {
    stopPageLeaveMonitoring()
  }

  //关闭定时器
  clearTimeout(timer)
  timer = null
  //关闭ws连接
  websocket?.disconnect()

  //判断是否为全流程面试
  let isFull = false
  if (redirect) {
    //全流程面试
    isFull = true
  }

  //获取全流程面试id
  const fullInterviewId = getLocalCache('fullInterviewId') || ''

  //将Hr面试数据写入数据库
  const data = await analyzeHrInterviewUsingPost({
    hrInterviewId: hrInterviewId.value as any,
    interviewDuration: currentDuration.value,
    interviewContentList: messages.value,
    isFull: isFull,
    fullInterviewId: fullInterviewId as any,
  })
  //清空面试时长
  currentDuration.value = 1
  if (data.data) {
    message.success(
      props.language === 'chinese'
        ? '面试完成！请稍后查看Hr面试记录页面查看面试分析报告'
        : 'Interview completed! Please check the Hr interview records page later for the analysis report'
    )
  }
}

/**
 * 取消面试
 */
const cancelInterview = async () => {
  // 如果正在监控页面离开，停止监控
  if (isMonitoringPageLeave.value) {
    stopPageLeaveMonitoring()
  }

  const data = await cancelHrInterviewUsingGet({
    hrInterviewId: hrInterviewId.value,
  })
  if (data.data) {
    message.success(
      props.language === 'chinese' ? '取消面试成功！' : 'Interview cancelled successfully!'
    )
    //跳转到首页
    goToHomePageOrFullScreen()
  } else {
    message.error(props.language === 'chinese' ? '取消面试失败！' : 'Failed to cancel interview!')
    //跳转到首页
    goToHomePageOrFullScreen()
  }
}

/**
 * 清空当前语音中的动作计数（开始新的回答时调用）
 */
const resetCurrentSpeakingCounts = () => {
  console.log('清空当前语音中的动作计数')
  // 重置当前语音段的动作计数
  for (let i = 0; i < faceActions.length; i++) {
    currentSpeakingActionCounts.faceActions[i] = 0
  }
  for (let i = 0; i < bodyActions.length; i++) {
    currentSpeakingActionCounts.bodyActions[i] = 0
  }

  // 同时重置FaceDetection组件中的计数
  if (faceRef.value) {
    faceRef.value.resetCounts()

    // 同时重置BodyDetection组件中的计数
    // 通过FaceDetection组件访问BodyDetection组件
    const bodyRef = faceRef.value.getBodyRef()
    if (bodyRef) {
      bodyRef.resetCounts()
    }
  }
}

/**
 * 开始说话
 */
const startSpeaking = () => {
  console.log('开始语音检测，重置所有动作计数')

  // 清空所有动作计数（总计数），每次语音都作为独立的检测
  for (let i = 0; i < faceActions.length; i++) {
    faceActions[i].count = 0
  }
  for (let i = 0; i < bodyActions.length; i++) {
    bodyActions[i].count = 0
  }

  // 清空当前语音中的动作计数
  resetCurrentSpeakingCounts()

  // 开启面部检测和躯体检测
  faceRef.value.startFace()
}

/**
 * 结束说话
 */
const stopSpeaking = () => {
  // 关闭面部检测，发送面部表情动作数据
  faceRef.value.stopFace()

  console.log('语音检测结束，结果如下:')
  console.log('面部动作当前计数:', JSON.stringify(currentSpeakingActionCounts.faceActions))
  console.log('躯体动作当前计数:', JSON.stringify(currentSpeakingActionCounts.bodyActions))

  // 更新总动作计数（将当前语音段的计数添加到总计数中）
  for (let i = 0; i < faceActions.length; i++) {
    faceActions[i].count += currentSpeakingActionCounts.faceActions[i]
    console.log(`${faceActions[i].name}: ${faceActions[i].count}次`)
  }

  for (let i = 0; i < bodyActions.length; i++) {
    bodyActions[i].count += currentSpeakingActionCounts.bodyActions[i]
    console.log(`${bodyActions[i].name}: ${bodyActions[i].count}次`)
  }

  // 不要在这里重置currentSpeakingActionCounts，而是在下一次开始说话时重置
}

/**
 * 面试时长格式化
 * @param seconds
 * @returns {`${string}:${string}`}
 */
const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 处理情感检测的方法
const handleEmotionDetected = (emotion) => {
  // 根据检测到的情感类型更新对应的值
  const maxValue = 100
  const incrementValue = 5
  const decrementValue = 3

  // 为检测到的情感添加值
  switch (emotion) {
    case 'confident':
      emotionData.confident = Math.min(emotionData.confident + incrementValue, maxValue)
      emotionData.calm = Math.max(emotionData.calm - decrementValue, 0)
      emotionData.nervous = Math.max(emotionData.nervous - decrementValue, 0)
      break
    case 'calm':
      emotionData.calm = Math.min(emotionData.calm + incrementValue, maxValue)
      emotionData.confident = Math.max(emotionData.confident - decrementValue, 0)
      emotionData.nervous = Math.max(emotionData.nervous - decrementValue, 0)
      break
    case 'nervous':
      emotionData.nervous = Math.min(emotionData.nervous + incrementValue, maxValue)
      emotionData.confident = Math.max(emotionData.confident - decrementValue, 0)
      emotionData.calm = Math.max(emotionData.calm - decrementValue, 0)
      break
  }
}

// 处理面部动作检测事件
const handleFaceActionDetected = (action) => {
  console.log('收到面部动作检测事件:', action)

  // 检查是否在语音过程中（面试官倾听状态）
  if (interviewerStatus.value === 3) {
    if (action.type) {
      // 处理面部动作
      switch (action.type) {
        case 'EYE_BLINK':
          currentSpeakingActionCounts.faceActions[0]++
          console.log(`眨眼计数更新: ${currentSpeakingActionCounts.faceActions[0]}`)
          break
        case 'MOUTH_PUFF':
          currentSpeakingActionCounts.faceActions[1]++
          console.log(`抿嘴计数更新: ${currentSpeakingActionCounts.faceActions[1]}`)
          break
        case 'EYE_UP_LEFT':
          currentSpeakingActionCounts.faceActions[2]++
          console.log(`左斜视计数更新: ${currentSpeakingActionCounts.faceActions[2]}`)
          break
        case 'EYE_UP_RIGHT':
          currentSpeakingActionCounts.faceActions[3]++
          console.log(`右斜视计数更新: ${currentSpeakingActionCounts.faceActions[3]}`)
          break
      }
    } else if (action.bodyAction) {
      // 处理躯体动作
      switch (action.bodyAction) {
        case 'ear':
          currentSpeakingActionCounts.bodyActions[0]++
          console.log(`摸耳朵计数更新: ${currentSpeakingActionCounts.bodyActions[0]}`)
          break
        case 'nose':
          currentSpeakingActionCounts.bodyActions[1]++
          console.log(`摸鼻子计数更新: ${currentSpeakingActionCounts.bodyActions[1]}`)
          break
      }
    }
  }
}

/**
 * 开始页面离开监控
 */
const startPageLeaveMonitoring = () => {
  // 检查是否为全流程面试
  if (!redirect) {
    console.log('非全流程面试，不进行页面监控')
    return
  }

  // 重置页面离开计数和状态
  pageLeaveCount.value = 0
  isMonitoringPageLeave.value = true
  isCurrentlyAway.value = false

  // 添加页面可见性变化事件监听
  document.addEventListener('visibilitychange', handleVisibilityChange)

  // 添加窗口失去焦点和获得焦点事件监听
  window.addEventListener('blur', handleWindowBlur)
  window.addEventListener('focus', handleWindowFocus)

  console.log('开始监控页面离开行为')

  // 显示监控提示
  message.success(
    props.language === 'chinese'
      ? '面试监控已开始，请不要频繁切换窗口或标签页，切换标签页或窗口5次将自动结束面试'
      : 'Interview monitoring started, please do not switch windows or tabs frequently. The interview will end automatically after 5 window/tab switches'
  )
}

/**
 * 处理页面可见性变化
 */
const handleVisibilityChange = () => {
  //只有处于当前监控页面才处理
  if (!isMonitoringPageLeave.value) return

  if (document.visibilityState === 'hidden') {
    // 用户离开页面
    isCurrentlyAway.value = true
    console.log('用户离开页面 (visibility hidden)')
  } else if (document.visibilityState === 'visible' && isCurrentlyAway.value) {
    // 用户返回页面，完成一次完整的切屏行为
    isCurrentlyAway.value = false
    recordPageLeave('页面切换')
  }
}

/**
 * 处理窗口失去焦点
 */
const handleWindowBlur = () => {
  //只有处于当前监控页面才处理
  if (!isMonitoringPageLeave.value) return

  // 标记用户已离开
  isCurrentlyAway.value = true
  console.log('用户离开页面 (window blur)')
}

/**
 * 处理窗口获得焦点
 */
const handleWindowFocus = () => {
  //只有处于当前监控页面才处理
  if (!isMonitoringPageLeave.value) return

  // 如果之前标记为离开，现在回来了，记录一次完整切屏
  if (isCurrentlyAway.value) {
    isCurrentlyAway.value = false
    recordPageLeave('窗口切换')
  }
}

/**
 * 记录页面离开并检查是否达到上限
 */
const recordPageLeave = (reason) => {
  //只有处于当前监控页面才处理
  if (!isMonitoringPageLeave.value) return

  pageLeaveCount.value++
  console.log(`完成一次完整的页面切换 (${reason}): 第 ${pageLeaveCount.value} 次`)

  // 每次切换都提示用户当前的切换次数
  message.info(
    props.language === 'chinese'
      ? `您已切换页面${pageLeaveCount.value}次，最多允许切换${MAX_PAGE_LEAVE_COUNT}次`
      : `You have switched pages ${pageLeaveCount.value} times. Maximum allowed: ${MAX_PAGE_LEAVE_COUNT} times`
  )

  // 如果达到最大次数，提示并取消面试
  if (pageLeaveCount.value >= MAX_PAGE_LEAVE_COUNT) {
    message.error(
      props.language === 'chinese'
        ? `您已切换页面${MAX_PAGE_LEAVE_COUNT}次，面试将自动结束`
        : `You have switched pages ${MAX_PAGE_LEAVE_COUNT} times, the interview will be automatically ended`
    )

    // 停止监控
    stopPageLeaveMonitoring()

    // 取消面试
    cancelInterview()
  } else if (pageLeaveCount.value >= MAX_PAGE_LEAVE_COUNT - 1) {
    // 当接近最大次数时发出警告
    message.warning(
      props.language === 'chinese'
        ? `警告：您已切换页面${pageLeaveCount.value}次，再切换${
            MAX_PAGE_LEAVE_COUNT - pageLeaveCount.value
          }次将自动结束面试`
        : `Warning: You have switched pages ${pageLeaveCount.value} times, ${
            MAX_PAGE_LEAVE_COUNT - pageLeaveCount.value
          } more time will end the interview`
    )
  }
}

/**
 * 停止页面离开监控
 */
const stopPageLeaveMonitoring = () => {
  //只有处于当前监控页面才处理
  if (!isMonitoringPageLeave.value) {
    console.log('没有正在进行的页面监控')
    return
  }

  // 移除事件监听
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  window.removeEventListener('blur', handleWindowBlur)
  window.removeEventListener('focus', handleWindowFocus)

  isMonitoringPageLeave.value = false
  isCurrentlyAway.value = false
  console.log('已停止页面离开监控')
}

// 在组件挂载时初始化
onMounted(async () => {
  //记录重定向
  redirect = (route.query.redirect as string) || ''

  //获取选择的面试官
  interviewerAvatar.value = getLocalCache('interviewerAvatar') as any
  interviewerId.value = getLocalCache('interviewerId') as any

  //获取对应面试官的虚拟数字人
  //执行动态导入
  const module = await videoMap[interviewerId.value][1]()
  interviewerMp4.value = module.default

  //初始化音频和情感数据
  commonStore.setAudioSpeed('')
  commonStore.setAudioEmotion('')

  // 初始化情感数据
  emotionData.confident = 0
  emotionData.calm = 0
  emotionData.nervous = 0

  // 确保动作计数初始化为0
  for (let i = 0; i < 4; i++) {
    currentSpeakingActionCounts.faceActions[i] = 0
  }
  for (let i = 0; i < 2; i++) {
    currentSpeakingActionCounts.bodyActions[i] = 0
  }

  console.log('组件已挂载，初始化完成')
})

//组件销毁时销毁时断开websocket连接
onBeforeUnmount(() => {
  // 断开websocket连接
  if (websocket) {
    websocket?.disconnect()
  }

  // 如果正在监控页面离开，停止监控
  if (isMonitoringPageLeave.value) {
    stopPageLeaveMonitoring()
  }
})
</script>

<style scoped>
.interview-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #f0f4f8, #d9e2ec);
  overflow: hidden;
  position: relative;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 主体区域样式 */
.interview-main {
  flex: 1;
  display: flex;
  padding: 10px;
  gap: 10px;
  overflow: hidden;
  height: 100vh;
}

/* 左侧面板 - 分析区域 */
.analysis-panel {
  width: 20%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 100%;
  overflow-y: auto;
}

.panel-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.panel-header {
  padding: 10px 12px;
  background: #f8fafc;
  border-bottom: 1px solid #e9eef6;
  display: flex;
  align-items: center;
  color: #334155;
  font-weight: 600;
  font-size: 14px;
}

.panel-header .anticon {
  margin-right: 8px;
  color: #4b5563;
}

.emotion-chart {
  width: 100%;
  height: 220px;
  margin-top: 5px;
}

.chart {
  width: 100%;
  height: 100%;
}

.face-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 10px;
}

.action-grid-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: #f8fafc;
  border-radius: 6px;
  transition: all 0.3s ease;
  border: 1px solid #e2e8f0;
  opacity: 1;
}

.action-grid-item.action-active {
  background: rgba(16, 185, 129, 0.05);
  border-color: rgba(16, 185, 129, 0.2);
}

.action-grid-item.current-speaking-active {
  border-color: #ff4d4f;
  box-shadow: 0 0 8px rgba(255, 77, 79, 0.4);
  animation: border-pulse 1.5s infinite;
  background-color: rgba(255, 77, 79, 0.05);
}

.action-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.action-name {
  font-weight: 500;
  color: #334155;
  font-size: 13px;
}

.action-count {
  color: #64748b;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.voice-analysis {
  padding: 16px 14px 10px 14px;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.voice-metric {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  background: #f7fafc;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(71, 149, 234, 0.08);
  padding: 12px 14px 10px 14px;
  margin-bottom: 0;
  position: relative;
}

.metric-icon {
  font-size: 18px;
  color: #4795ea;
  margin-right: 8px;
  vertical-align: middle;
}

.metric-title {
  font-size: 14px;
  font-weight: 600;
  color: #334155;
  margin-bottom: 6px;
  margin-left: 2px;
}

.metric-value {
  font-size: 15px;
  font-weight: bold;
  color: #10b981;
  background: #e6fffb;
  border-radius: 4px;
  padding: 2px 10px;
  margin-left: 10px;
  margin-bottom: 6px;
  display: inline-block;
}

.metric-bar {
  width: 100%;
  height: 8px;
  background: #e9eef6;
  border-radius: 4px;
  margin-top: 2px;
  overflow: hidden;
}

.metric-bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.5s;
}

.metric-bar-fill.speed {
  background: linear-gradient(90deg, #4795ea, #10b981);
}

.metric-bar-fill.emotion {
  background: linear-gradient(90deg, #ffb347, #ff7a45, #f56565);
}

.face-actions-grid,
.body-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 10px;
}

.metric-label {
  font-weight: 500;
  color: #334155;
  font-size: 14px;
}

.meter-label {
  font-size: 14px;
  color: #64748b;
}

/* 中间面板 - 虚拟人和摄像头 */
.center-panel {
  width: 56%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 100%;
}

.digital-human-container {
  flex: 2.5;
  background: linear-gradient(180deg, #111827, #1f2937);
  background-size: cover;
  background-position: center;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.interviewer-status {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 6px 10px;
  border-radius: 16px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  z-index: 5;
  backdrop-filter: blur(4px);
}

.status-indicator {
  display: block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #10b981;
  animation: pulse 2s infinite;
}

.digital-human {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.interviewer-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0));
  padding: 12px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  z-index: 5;
}

.interviewer-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.interviewer-details h3 {
  margin: 0 0 2px;
  font-size: 15px;
  font-weight: 600;
}

.interviewer-details p {
  margin: 0;
  font-size: 12px;
  opacity: 0.8;
}

.interview-controls-container {
  position: absolute;
  left: 50%;
  bottom: 40px;
  transform: translateX(-50%);
  z-index: 10;
}

.interview-timer {
  margin-top: 10px;
}

.interview-duration {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 8px;
}

.user-camera-container {
  flex: 1.2;
  background: #1f2937;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  min-height: 220px;
  max-height: 300px; /* 限制最大高度 */
}

.camera-content {
  flex: 1;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  height: 220px; /* 稍微增加高度 */
}

/* 确保视频和检测内容正确对齐 */
.camera-content :deep(.video-canvas-container) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  padding: 10px 0; /* 添加上下内边距 */
}

.camera-content :deep(video) {
  object-fit: contain !important; /* 强制使用contain属性 */
  max-height: none !important; /* 移除高度限制 */
  width: auto !important; /* 允许宽度自动调整 */
  margin: 0 auto; /* 居中显示 */
  height: 100% !important; /* 填满高度 */
}

.camera-content :deep(canvas) {
  position: absolute;
  left: 50% !important; /* 使用50%左偏移 */
  transform: translateX(-50%) rotateY(180deg) !important; /* 添加X轴平移实现居中 */
  -webkit-transform: translateX(-50%) rotateY(180deg) !important;
  -moz-transform: translateX(-50%) rotateY(180deg) !important;
  width: auto !important; /* 自动宽度 */
  height: 100% !important; /* 填满高度 */
  max-width: 100%; /* 限制最大宽度 */
  max-height: none !important; /* 移除高度限制 */
  z-index: 10;
}

.camera-header {
  background: rgba(0, 0, 0, 0.7);
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  color: white;
  font-size: 12px;
}

.recording-indicator {
  margin-left: auto;
  color: #f56565;
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 4px;
  animation: blink 1.5s infinite;
}

.recording-indicator.video-recording {
  color: #1890ff;
  font-weight: bold;
  animation: blink 0.8s infinite;
}

.camera-tips {
  background: rgba(0, 0, 0, 0.7);
  padding: 6px 12px;
  font-size: 11px;
  color: #e2e8f0;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 右侧面板 - 对话区 */
.chat-panel {
  width: 24%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  max-height: 100%;
}

/* 退出按钮 */
.exit-button {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 100;
}

.control-btn {
  display: flex;
  align-items: center;
  font-weight: 500;
}

/* 弹窗样式 */
.custom-modal :deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

.custom-modal :deep(.ant-modal-header) {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
}

.custom-modal :deep(.ant-modal-title) {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.custom-modal :deep(.ant-modal-body) {
  padding: 20px;
}

.modal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.modal-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.modal-icon.warning {
  color: #faad14;
}

.modal-icon.success {
  color: #52c41a;
}

.modal-message {
  margin-bottom: 20px;
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.modal-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.modal-footer button {
  min-width: 80px;
  height: 36px;
  font-size: 14px;
  border-radius: 6px;
}

/* 动画效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(16, 185, 129, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 响应式布局调整 */
@media (max-width: 1366px) {
  .analysis-panel {
    width: 22%;
  }

  .center-panel {
    width: 46%;
  }

  .chat-panel {
    width: 32%;
  }
}

@media (max-width: 1200px) {
  .interview-main {
    flex-direction: column;
    height: auto;
    overflow-y: auto;
  }

  .analysis-panel,
  .center-panel,
  .chat-panel {
    width: 100%;
    max-height: none;
  }

  .digital-human-container {
    height: 400px;
  }

  .user-camera-container {
    height: 180px;
  }
}

.current-speaking-count {
  display: inline-block;
  color: #ff4d4f;
  font-weight: 700;
  margin-left: 4px;
  background-color: rgba(255, 77, 79, 0.15);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  animation: pulse-text 1.5s ease-in-out infinite;
  box-shadow: 0 0 5px rgba(255, 77, 79, 0.3);
  min-width: 28px;
  text-align: center;
}

@keyframes pulse-text {
  0%,
  100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.9;
    transform: scale(1.1);
  }
}

/* 当检测到动作并且当前计数大于0时添加脉动边框效果 */
.action-grid-item.speaking-detected {
  border-color: #ff4d4f;
  box-shadow: 0 0 8px rgba(255, 77, 79, 0.4);
  animation: border-pulse 1.5s infinite;
  background-color: rgba(255, 77, 79, 0.05);
}

@keyframes border-pulse {
  0%,
  100% {
    border-color: rgba(255, 77, 79, 0.9);
    box-shadow: 0 0 8px rgba(255, 77, 79, 0.4);
  }
  50% {
    border-color: rgba(255, 77, 79, 0.6);
    box-shadow: 0 0 4px rgba(255, 77, 79, 0.2);
  }
}

/* 添加一个高亮效果，表示当前检测到的动作 */
.action-grid-item.detection-active {
  border-color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.05);
  box-shadow: 0 0 0 1px rgba(255, 77, 79, 0.3);
  transition: all 0.2s ease;
}

/* 雷达图下方情感百分比展示条样式 */
.emotion-percentages {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0 0 0;
  gap: 8px;
}

.emotion-percentage-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 6px;
}

.emotion-label {
  font-size: 12px;
  color: #334155;
  min-width: 32px;
}

.emotion-bar {
  flex: 1;
  height: 8px;
  background: #e9eef6;
  border-radius: 4px;
  overflow: hidden;
  margin: 0 4px;
}

.emotion-bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.5s;
}

.emotion-bar-fill.confident {
  background: linear-gradient(90deg, #4795ea, #10b981);
}

.emotion-bar-fill.calm {
  background: linear-gradient(90deg, #a0aec0, #38b2ac);
}

.emotion-bar-fill.nervous {
  background: linear-gradient(90deg, #ff7a45, #f56565);
}

.emotion-value {
  font-size: 18px;
  font-weight: bold;
  color: #4795ea;
  margin-bottom: 2px;
}

.emotion-desc {
  font-size: 12px;
  color: #64748b;
  margin-top: 2px;
}

/* 添加面试官生成问题的加载动画 */
.generating-question-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.generating-question-content {
  text-align: center;
}

.generating-question-content p {
  margin: 10px 0 0;
  color: white;
  font-size: 14px;
  font-weight: 500;
}
</style>
